package com.panshi.controller.qiniuyun;

import com.panshi.qny.QiniuUtils;
import com.panshi.qny.UploadImageImp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/qiniu")
public class QiniuController {

    @Resource
    private UploadImageImp uploadImageImp;

    @PostMapping("/upload")
    @ResponseBody
    public Map<String,Object> uploadImg(@RequestParam(required = false) MultipartFile imgFile) throws IOException {

        log.info("file=={}",imgFile);

        Map<String,Object> map = new HashMap<>();

        //获取文件的名称
        String fileName = imgFile.getOriginalFilename();

        //使用工具类根据上传文件生成唯一的图片名称
        String imgName = QiniuUtils.getRandomImgName(fileName);

        log.info("--------------------------------fileName:{}",fileName);
        log.info("--------------------------------imgName:{}",imgName);

        if(!imgFile.isEmpty()){

            FileInputStream stream = (FileInputStream) imgFile.getInputStream();

            String path = uploadImageImp.uploadQNImg(stream,imgName);

            path = "http://"+path;

            log.info("七牛云返回的图片链接*****************：{}",path);

            map.put("error",0);
            map.put("url",path);

            return map;

        }

        map.put("error",1);
        map.put("message","上传失败");

        return map;

    }

}
